package com.example.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import com.example.bean.UserBean;

import java.util.Date;  //使用java中的new Date方法Date.now()得的是现在的毫秒数，格式和mysql上的datetime不一样（就算是用timestamp也会报错）
//因此转用javascript中的moment库
import java.util.List;
@Service("userDaoImpl") //@Service为给类增加别名
public class UserDaoImpl implements UserDao {
    @Autowired //是用在JavaBean中的注解，通过byType形式，用来给指定的字段或方法注入所需的外部资源。
    private JdbcTemplate jdbcTemplate; //jdbc连接工具类
    //查询所有数据
    @Override
    public List<UserBean> findAll() {
        String sql = "select * from user";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<UserBean>(UserBean.class));
    }


    //查询指定name
    @Override
    public List<UserBean> findByUserName(String username) {
        String sql = "select * from user where username=?";
        Object[] params = new Object[]{username};
        return jdbcTemplate.query(
                sql,
                params,
                new BeanPropertyRowMapper<UserBean>(UserBean.class));
    }

    //增
    @Override
    public boolean addUser(UserBean user) {
        String username=user.getUsername();
        List<UserBean> users = this.findByUserName(username);
        if(users.size()>0){
            return false;
        }
        String sql = "insert into user(username,password,email,tel,createTime,updateTime)values(?,?,?,?,NOW(),NOW())";
        Object[] params = {user.getUsername(),user.getPassword(),user.getEmail(),user.getTel()};
        return jdbcTemplate.update(sql, params)>0;
    }

    //    改
    @Override
    public boolean updateByUserName(String password,String username) {
        String sql = "update user set password=? where username=?";
        Object[] params = {username,password};
        return jdbcTemplate.update(sql,params)>0;

    }

    //改
    @Override
    public boolean updateUserInfo(String currentusername,String em,String te,String pwd) {
        String sql = "UPDATE user SET email=?, tel=?, password=?, updateTime=NOW() WHERE username=?";
        Object[] params = {
                em,te,pwd,
                currentusername
        };
        return jdbcTemplate.update(sql, params) > 0;
    }

    public boolean levelUp(String username) {
        String sql = "UPDATE user SET exp = exp + 1 WHERE username = ?";
        Object[] params = new Object[]{username};
        // 执行更新操作，如果影响的行数大于0，则返回true
        return jdbcTemplate.update(sql, params) > 0;
    }




    //删
    @Override
    public boolean deleteByUserName(String username) {
        String sql = "delete from user where username=?";
        Object[] params = {username};
        return jdbcTemplate.update(sql,params)>0;
    }


}
